from rest_framework import viewsets

from . import models
from library_app.models import Category, Author, Book
from library_app.serializers import CategorySerializer, AuthorSerializer, BookReadSerializer, BookWriteSerializer


class BookViewSet(viewsets.ModelViewSet):
    """
    图书视图
    返回图书分类，作者，价格，总价格(total_price)
    """

    def get_serializer_class(self):
        if self.request.method in ['GET', 'HEAD']:
            return BookReadSerializer
        return BookWriteSerializer

    queryset = Book.objects.all().order_by('id')
    serializer_class = get_serializer_class
    # 查询字段
    filter_fields = ('title',)

    def list(self, request, *args, **kwargs):
        """
        :return: response相应数据
        :query_books:查询的到的书籍
        :total_price:总价格
        :price:临时价格
        """

        # 重写list，考虑效率问题，图书计算写在视图中
        response = super(BookViewSet, self).list(request, *args, **kwargs)

        query_books = models.Book.objects.all()
        total_price = 0
        for item in query_books:
            price = item.price
            total_price += price
        response.data['total_price'] = '%.2f' % total_price

        return response


class CategoryViewSet(viewsets.ModelViewSet):
    """分类视图"""
    queryset = Category.objects.all().order_by('id')
    serializer_class = CategorySerializer


class AuthorViewSet(viewsets.ModelViewSet):
    """作者视图"""
    queryset = Author.objects.all().order_by('id')
    serializer_class = AuthorSerializer
